package com.situ.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.situ.mall.api.product.ProductClient;
import com.situ.mall.common.util.Result;
import com.situ.mall.pojo.entity.product.Product;
import com.situ.mall.pojo.entity.user.Collect;
import com.situ.mall.user.mapper.CollectMapper;
import com.situ.mall.user.pojo.query.CollectQuery;
import com.situ.mall.user.service.ICollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CKX
 * @since 2024-10-17
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private ProductClient productClient;

    @Override
    public List<Product> selectList(CollectQuery collectQuery) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", collectQuery.getUserId());
        List<Collect> collectList = collectMapper.selectList(queryWrapper);
        List<Product> productList = new ArrayList<>();
        for (Collect collect : collectList) {
            Long id = collect.getProductId();
            Result<Product> result = productClient.selectById(id);
            if (result.getCode() == 0) {
                Product product = result.getData();
                productList.add(product);
            }
        }
        return productList;
    }

    @Override
    public int add(Collect collect) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", collect.getUserId());
        queryWrapper.eq("product_id", collect.getProductId());
        Collect collectProduct = collectMapper.selectOne(queryWrapper);
        if (collectProduct == null) {
            collectMapper.insert(collect);
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public void delete(Collect collect) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", collect.getProductId());
        queryWrapper.eq("user_id", collect.getUserId());
        collectMapper.delete(queryWrapper);
    }
}
